const customTags = ['for'];

export function templateToDom(template, state) {
    let oDiv = document.createElement('div');
    oDiv.innerHTML = template;
    Array.from(oDiv.getElementsByTagName('div')[0].childNodes).forEach(node => {
        if (node.nodeType === 1) {
            if (customTags.includes(node.nodeName.toLocaleLowerCase())) {
                switch (node.nodeName.toLocaleLowerCase()) {
                    case 'for':
                        vFor(node, state);
                        break;
                    default:
                        break;
                }
            }
        }
    })
    return oDiv;
}

function vFor(node, state) {
    let data = node.getAttribute('data'),
        realTag = node.getAttribute('tag'),
        className = node.getAttribute('class');
    let oFor = document.createElement(realTag);
    oFor.className = className ? className : '';
    replaceNode(node, oFor, state[data], /\{(.*?)\}/g);
}

function replaceNode(node, dom, data, reg) {
    let innerHTML = node.innerHTML;
    let htmlStr = '';
    data.forEach(item => {
        htmlStr += innerHTML.replace(reg, (node, key) => {
            return item[key.trim()];
        })
    })
    dom.innerHTML = htmlStr;
    node.parentNode.replaceChild(dom, node);
}